package com.jame.basics.thread.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : Jame
 * @date : 2021-01-10 17:47
 **/
public class OrderThread {
    public static void main(String[] args) {
        Print print = new Print();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                print.printA();
            }
        },"线程A").start();   new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                print.printB();
            }
        },"线程B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                print.printC();
            }
        }, "线程C").start();
    }
}

class Print {
    String sing = "A";
    private Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            while (!sing.equals("A")) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"=="+"A");
            sing = "B";
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (!sing.equals("B")) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"=="+"B");
            sing = "C";
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (!sing.equals("C")) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"=="+"C");
            sing = "A";
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
